package fatworm.storage.table;

import fatworm.storage.file.*;
import fatworm.tx.*;
import fatworm.util.*;

public class VarFile
{
    private TableInfo ti;
    private Transaction tx;
    private String filename;
    private String fldname;
    private VarPage vp = null;
    private int curBlkNum;

    public VarFile(TableInfo ti, String fldname, Transaction tx)
    {
        this.ti = ti;
        this.tx = tx;
        filename = ti.fileName() + "." + fldname;
        if (tx.size(filename) == 0)
            appendBlock();
        moveTo(0);
    }
    public void close()
    {
        vp.close();
    }
    public byte[] getBytes()
    {
        return vp.getBytes();
    }
    public void setBytes(byte[] val)
    {
        vp.setBytes(val);
    }
    public void insert(int vallen)
    {
        while (!vp.insert(vallen))
        {
            if (atLastBlock())
                appendBlock();
            moveTo(curBlkNum);
        }
    }
    public void moveToVid(VID vid)
    {
        Lib.debug("VarFile.moveToVid()" + vid);
        moveTo(vid.blknum);
        vp.moveToId(vid.id);
    }
    public VID currentVID()
    {
        int id = vp.currentId();
        return new VID(curBlkNum, id);
    }
    private void moveTo(int b)
    {
        if (vp != null)
            vp.close();
        curBlkNum = b;
        Block blk = new Block(filename, curBlkNum);
        vp = new VarPage(blk, tx);
    }
    private boolean atLastBlock()
    {
        return curBlkNum == tx.size(filename) - 1;
    }
    private void appendBlock()
    {
        VarPageFormatter fmtr = new VarPageFormatter();
        tx.append(filename, fmtr);
    }
}
